package com.zj.core.services

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.v4.content.FileProvider
import com.zj.core.base.BaseApplication
import java.io.File

class InstallApkReceiver: BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        val filePath=intent?.getStringExtra("filePath")
        val fileName=intent?.getStringExtra("fileName")
        installApk(filePath+fileName)
    }

    private fun installApk(path: String) {
        Intent(Intent.ACTION_VIEW).let {
            it.flags = Intent.FLAG_ACTIVITY_NEW_TASK

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val apkUri = FileProvider.getUriForFile(BaseApplication.context!!, BaseApplication.context!!.packageName+".fileprovider", File(path))
                it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                it.setDataAndType(apkUri, "application/vnd.android.package-archive")
            } else {
                it.setDataAndType(Uri.fromFile(File(path)), "application/vnd.android.package-archive")
            }
            BaseApplication.context?.startActivity(it)
        }
    }
}